<template>
	<view>
		<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
			<u-avatar class="avatar" size="162" shape="square" :src="avatar"></u-avatar>
		</button>
		<view class="avatarButton">
			<span>昵称：</span>
			<input type="nickname" class="weui-input" :value="screenName" placeholder="请输入昵称" @blur="bindblur" />
		</view>
		<view class="loginButton">
			<u-button type="success" :ripple="true" :custom-style="btnStyle" @click="updateUserInfo">
				保存
			</u-button>
		</view>
	</view>
</template>

<script>
	import {
		modifyUserWxInfo,
		uploadUserAvatar
	} from "apis/farmer/user.js"
	import {
		mapState,
		mapMutations
	} from "vuex"
	export default {
		data() {
			return {
				avatar: '',
				screenName: ''
			}
		},
		computed: {
			...mapState({
				oldScreenName: state => state.userStore.screenName,
				oldAvatar: state => state.userStore.avatar
			}),
		},
		onLoad() {
			this.avatar = this.oldAvatar
			this.screenName = this.oldScreenName
		},
		methods: {
			...mapMutations(['setScreenName','setAvatar']),
			async updateUserInfo() {
				if (!this.screenName.length || !this.avatar.length) {
					this.$errorMsg('请补充头像昵称')
					return 0
				}
				const {
					screenName,
					avatar
				} = this

				const {
					code,
					msg,
				} = await modifyUserWxInfo(screenName, avatar)
				if (code === 200) {
					this.setAvatar(avatar)
					this.setScreenName(screenName)
					uni.switchTab({
						url: '/pages/mine/mine'
					})
				} else {
					this.$errorMsg(msg)
				}
			},
			bindblur(e) {
				this.screenName = e.detail.value
			},
			/* 上传用户头像 */
			async onChooseAvatar(e) {
				const {
					avatarUrl
				} = e.detail
				const result = await uploadUserAvatar(avatarUrl)
				const {
					code,
					data,
					msg
				} = JSON.parse(result)
				if (code !== 200) return this.$errorMsg(msg)
				this.avatar = data
			}
		}
	}
</script>

<style>
	.avatarButton {
		display: flex;
		height: 100rpx;
		box-sizing: border-box;
		align-items: center;
		justify-content: center;
		padding: 0 5vw;
		border-top: 1px solid #dadada;
		border-bottom: 1px solid #dadada;
	}

	.avatar-wrapper {
		padding: 0;
		width: 162rpx;
		background: transparent;
		margin: 50rpx 0;
		position: relative;
		left: 50%;
		transform: translate(-50%, 0);
	}

	.container {
		display: flex;
	}

	.loginButton {
		border: 0;
		width: 50vw;
		position: relative;
		margin: 0 auto;
		top: 40rpx;
	}

	.weui-input {
		width: 60vw;
		padding: 0 40rpx;
	}
</style>
